/*
 * Copyright (c) MengChang Wang <wangmengchang@gmail.com>
 * Webpage:  http://www.journalhome.com/texpen/
 *
 *
*/
#include "headers/mainwindow.h"
#include <QProcess>
#include <QAction>
#include <QTextDocument>
#include <QTextCursor>
#include <QVector>
#include <QDebug>
#include <QtConcurrentRun>
#include <QFile>
#include <QWebFrame>


//QtConcurrent::run

void asyncRun(MainWindow* wnd, QString& prog, QStringList& arglist){
    wnd->proc = new QProcess;
    QObject::connect(wnd->proc,SIGNAL(readyReadStandardOutput()),
                     wnd,SLOT(readProcOutput())
                     );
    wnd->proc->setProcessChannelMode(QProcess::ForwardedChannels);
    wnd->proc->startDetached(prog,arglist);

}


void MainWindow::onCmdFinish(){
    runCommand->setIcon(QIcon(":/icons/icons/24x24/media-playback-start.png"));
    runCommand->setStatusTip(tr("Run: %1").arg(Settings.theCommand));
    runCommand->setText(tr("Build"));
}

void MainWindow::onRun(){

    //run->start();
    ApplySettings();//update system variables in the command
    if(run->isCmdRunning()){
        run->getProc()->kill();
        runCommand->setIcon(QIcon(":/icons/icons/24x24/media-playback-start.png"));
        runCommand->setStatusTip(tr("Run: %1").arg(Settings.theCommand));
        runCommand->setText(tr("Build"));
        equation->setHtml("Building terminated.");
        //equationview->hide();
    }else{
        equationview->setWindowTitle("Build Information");
        equation->setHtml("running...<br>");
        equationview->show();
        run->run();
        runCommand->setIcon(QIcon(":/icons/icons/24x24/media-playback-stop.png"));
        runCommand->setStatusTip(tr("Stop building"));
        runCommand->setText(tr("Stop building"));
    }
    return;
}

void MainWindow::readProcOutput(){
    qDebug()<<"MainWindow::readProcOutput()..."<<endl;
//    QByteArray ba = proc->readAllStandardOutput();
//    ba += proc->readAllStandardError();
//    ba += proc->readAll();
//    qDebug()<<"ba="<<ba<<endl;
    QByteArray ba = run->getProc()->readAll();
    QString html="";
    html.append(ba);
    html.replace("\n","<br>");
    html = equation->page()->mainFrame()->toHtml()+html;
    equation->setHtml(html);
    //equation->scroll(0,2536);
    equation->page()->mainFrame()->setScrollPosition(QPoint(0,25530));
    equationview->show();
}
